//
//  VGAppleLoginManager.swift
//  vgbox
//
//  Created by 宋海胜 on 2020/3/3.
//  Copyright © 2020 Swift Xcode. All rights reserved.
//

import UIKit
import AuthenticationServices

/// 苹果登陆管理类
class VGAppleLoginManager: UIView {

    public var getAppleUserIDClosure: ((String) -> Void)?
    fileprivate var btnSuperView: UIView!
    
    
    init(frame: CGRect, view: UIView) {
        super.init(frame: frame)
        self.btnSuperView = view
        self.configButton()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    
    func configButton() {
        
        if #available(iOS 13.0, *) {
            let authorizationButton = ASAuthorizationAppleIDButton()
            authorizationButton.addTarget(self, action: #selector(authorizationButtonClick), for: .touchUpInside)
            self.addSubview(authorizationButton)
            authorizationButton.snp.makeConstraints { (make) in
                make.edges.equalToSuperview()
            }
            self.addSubview(authorizationButton)
        } else {
            // Fallback on earlier versions
        }
    }
        
        
    @objc func authorizationButtonClick() {
        
        if #available(iOS 13.0, *) {
            
            let appleIDProvider = ASAuthorizationAppleIDProvider()
            let request = appleIDProvider.createRequest()
            request.requestedScopes = [.fullName, .email]
            let auth = ASAuthorizationController(authorizationRequests: [request])
            auth.delegate = self
            auth.presentationContextProvider = self
            auth.performRequests()
        }
    }
}

// ASAuthorizationControllerPresentationContextProviding 设置上下文，管理视图弹出在哪里
@available(iOS 13.0, *)
extension VGAppleLoginManager: ASAuthorizationControllerPresentationContextProviding {
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return self.superview!.window!
    }
}

// ASAuthorizationControllerDelegate 处理数据回调
@available(iOS 13.0, *)
extension VGAppleLoginManager: ASAuthorizationControllerDelegate {
    
    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        /*
         NSString *errorMsg = nil;
         switch (error.code) {
         case ASAuthorizationErrorCanceled:
         errorMsg = @"用户取消了授权请求";
         break;
         case ASAuthorizationErrorFailed:
         errorMsg = @"授权请求失败";
         break;
         case ASAuthorizationErrorInvalidResponse:
         errorMsg = @"授权请求响应无效";
         break;
         case ASAuthorizationErrorNotHandled:
         errorMsg = @"未能处理授权请求";
         break;
         case ASAuthorizationErrorUnknown:
         errorMsg = @"授权请求失败未知原因";
         break;
         }
         */
        print(error.localizedDescription)
    }
    
    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        
        if authorization.credential.isKind(of: ASAuthorizationAppleIDCredential.self) {
            
            let apple: ASAuthorizationAppleIDCredential = authorization.credential as! ASAuthorizationAppleIDCredential
            //返回得到的user 信息
            let userIdentifier: String = apple.user
            let realUserStatus: ASUserDetectionStatus = apple.realUserStatus
            let state: String = apple.state ?? ""
            let email: String = apple.email ?? ""
            var authorizationCode: String = ""
            var fullName: NSPersonNameComponents?
            var identityToken: Data?
            
            if let n = apple.fullName {
                fullName = n as NSPersonNameComponents
            }
            
            //用于后台向苹果服务器验证身份信息
            if let t = apple.identityToken {
                identityToken = t
            }
            if let code = apple.authorizationCode, let s = String.init(data: code, encoding: String.Encoding.utf8)  {
                authorizationCode = s
            }
            getAppleUserIDClosure?(userIdentifier)
            print(userIdentifier, fullName, email, identityToken, state, authorizationCode, realUserStatus)
        } else if authorization.credential.isKind(of: ASPasswordCredential.self) {
            let pass: ASPasswordCredential = authorization.credential as! ASPasswordCredential
            let username: String = pass.user
            let password: String = pass.password
            print(username, password)
        }
    }
}



